package com.nowcoder.community.service;

import com.nowcoder.community.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DataService {

    @Autowired
    private RedisTemplate redisTemplate;

    private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

    //将指定的ip传入UV
    public void recordUV(String ip){
        //构造键前缀 + 当前日期
        String uvKey = RedisUtil.getUVKey(df.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(uvKey,ip);
    }

    //统计日期范围内的IP数量
    public long calculateUV(Date start,Date end){
        if (start == null || end == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        //遍历日期(利用Calendar)，整理该日期范围内的key
        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while(!calendar.getTime().after(end)){
            String key = RedisUtil.getUVKey(df.format(calendar.getTime()));
            keyList.add(key);
            calendar.add(Calendar.DATE,1);
        }
        //生成一个新key，然后利用HyperLogLog把数据合并到新key中
        String key = RedisUtil.getUVKey(df.format(start),df.format(end));
        redisTemplate.opsForHyperLogLog().union(key,keyList.toArray());
        //返回结果
        return redisTemplate.opsForHyperLogLog().size(key);
    }


    //将指定的用户传入DAU
    public void recordDAU(int userId){
        //构造key，当前日期
        String key = RedisUtil.getDAUKey(df.format(new Date()));
        redisTemplate.opsForValue().setBit(key,userId,true);
    }

    //统计指定日期内的DAU
    public long calculateDAU(Date start,Date end){
        if (start == null || end == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        //遍历日期(利用Calendar)，整理该日期范围内的key
        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while(!calendar.getTime().after(end)){
            String key = RedisUtil.getDAUKey(df.format(calendar.getTime()));
            keyList.add(key.getBytes());
            calendar.add(Calendar.DATE,1);
        }
        //进行或运算
        Object obj = redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                //构造一个新key，对所有bitmap进行or运算，结果合并到新key
                String key = RedisUtil.getDAUKey(df.format(start),df.format(end));
                connection.bitOp(RedisStringCommands.BitOperation.OR,
                        key.getBytes(),keyList.toArray(new byte[0][0]));
                return connection.bitCount(key.getBytes());
            }
        });

        //返回结果
        return (long) obj;
    }






}
